<template>
	<view class="file_upload">
		<view v-if="isUpdate!=2"
			style="border:1px solid #e5e7eb;display: flex;justify-content: center;align-items: center; height: 65rpx;"
			@click="handleUpload">
			<uni-icons type="plusempty" size="20" style="margin-right: 10rpx;"></uni-icons>
			{{text}}
		</view>
		<view style="margin-top: 10rpx;display: flex;flex-direction: column;gap:16rpx;overflow: hidden;"
			v-if="fileList&&fileList.length">
			<view style="display: flex;gap:10rpx;align-items: center;" v-for="(item,index) in fileList" :key="index">
				<view v-if="!item.previewUrl" style="flex:1;word-break: break-word;" @click="handleDonwload(item)">
					{{item.name}} {{bytesToMB(item.size || item.fileSize)}}
				</view>
				<view v-else style="flex:1;word-break: break-word;" @click="handlePreview(item)">
					{{item.name}}
				</view>
				<view v-if="item.previewUrl">
					<uni-icons type="download" size="32" @click="handleDonwload(item)"
						style="margin-right:10rpx"></uni-icons>
				</view>
				<view v-if="isUpdate!=2">
					<uni-icons type="closeempty" size="24" style="color:red" @click="handleDeleteFile(item,index)"
						v-if="isDel || item.fileType=='add'"></uni-icons>
				</view>
			</view>
		</view>
		<xe-upload ref="XeUpload" :options="{}" @callback="handleUploadCallback"></xe-upload>
	</view>
</template>

<script>
	import {
		upload,
		postFormAction,
		downloadFile
	} from '@/utils/request.js';
	import XeUpload from '../xe-upload/components/xe-upload/xe-upload.vue'
	import {
		Api
	} from '@/utils/Api'
	export default {
		components: {
			XeUpload,
		},
		props: {
			type: {
				type: String,
				default: ''
			},
			text: {
				type: String,
				default: '上传文件'
			},
			isDel: {
				type: Boolean,
				default: true
			},
			msgId: {
				type: [String, Number],
				default: ''
			},
			isUpdate: {
				type: [Number],
				default: 0
			}
		},
		data() {
			return {
				fileList: []
			}
		},
		methods: {
			handlePreview(item) {
				uni.navigateTo({
					url: `/application/preview?record=${JSON.stringify({url: item.previewUrl, name:item.name})}`,
				});
			},
			//点击上传
			handleUpload() {
				// 使用默认配置则不需要传入第二个参数
				this.$refs.XeUpload.upload('file', {});
			},
			//上传附件回调
			handleUploadCallback({
				type,
				data
			}) {
				console.log("data", data)
				console.log("type", type)
				if (type == 'choose') {
					// this.fileList = this.fileList.concat(data)

					this.handleUploadFile(data)

				} else if (type == 'success') {
					console.log("success")
				}
			},
			//删除回复上传的文件
			async handleDeleteFile(item, index) {
				try {
					if (this.type == 'plan') {
						uni.showLoading({
							title: '',
							mask: true,
						})
						const res = await postFormAction('/plan/attachment/del', {
							id: item.id
						})
						uni.hideLoading()
					} else {
						if (item.fileType != 'add') {
							uni.showLoading({
								title: '',
								mask: true,
							})
							let res = null
							if (this.type == 'externalEmail') {
								res = await postFormAction('/email/delAttachment', {
									attId: item.id,
									mailId: this.msgId
								})
							} else {
								res = await postFormAction('/message_oa/delAttachment', {
									attId: item.id,
									msgId: this.msgId
								})
							}
							console.log('handleDeleteFile', res)
							uni.hideLoading()
							if (res.code != 200) {
								uni.showToast({
									icon: "none",
									title: res.msg || '操作失败',
								});
								return
							} else {
								uni.showToast({
									icon: "none",
									title: res.msg || '操作成功',
								});
							}
						}

					}
					this.fileList.splice(index, 1)
				} catch (e) {
					uni.hideLoading()
				}
			},
			//上传文件
			async handleUploadFile(data) {
				data.forEach(async (item, index) => {
					try {
						uni.showLoading({
							title: '上传中',
							mask: true
						});
						let res = {}
						if (this.type == 'plan') {
							res = await upload('/plan/attachment/upload', item.tempFilePath)
						} else if (this.type == 'externalEmail') {
							res = await upload('/email/upload', item.tempFilePath)
						} else {
							res = await upload('/message_oa/upload', item.tempFilePath)
						}
						uni.hideLoading()
						const {
							data
						} = res
						this.fileList.push({
							...data,
							fileType: 'add'
						})
						console.log("handleUploadFile-res", index, '-', res)
					} catch (e) {
						uni.hideLoading()
					}
				})
			}, //下载
			async handleDonwload(record) {
				let info = uni.getStorageSync("loginInfo");
				if (info.loginInfo.isMobileForbidDownload) {
					uni.showToast({
						icon: "none",
						title: "手机端禁止下载文件",
					});
					return;
				}
				if (!record.visualPath && !record.diskName) {
					return
				}
				const path = record.visualPath + record.diskName;
				const fileName = record.name;
				//这里填写接口地址
				const url = path ?
					Api.baseUrl + (path && path.startsWith('/') ? path : `/${path}`) :
					'';
				// #ifdef H5
				if (this.type == 'plan') {
					const data = await postFormAction('/plan/attachment/download', {
						id: record.id
					}, 'post', {}, {
						responseType: 'arraybuffer'
					})
					console.log("data", data)
					const blob = new Blob([data], {
						type: 'application/png;charset=utf-8'
					});
					const a = document.createElement('a');
					const href = window.URL.createObjectURL(blob); // 创建下载连接
					a.href = href;
					a.download = fileName;
					document.body.appendChild(a);
					a.click();
					document.body.removeChild(a); // 下载完移除元素
				} else {
					let doma = document.createElement("a");
					doma.download = ''; // 设置下载的文件名，默认是'下载'
					doma.target = "_blank"
					doma.href = url; //临时路径再保存到本地
					document.body.appendChild(doma);
					doma.click();
					doma.remove(); // 下载之后把创建的元素删除
				}
				// #endif
				console.log("开始下载");
				// #ifdef APP || MP-WEIXIN 
				if (this.type == 'plan') {
					const res = await downloadFile(`/plan/attachment/download?id=${record.id}`)
					console.log("_res", res)
					if (res.statusCode === 200) {
						console.log('下载成功：', res.tempFilePath);

						//下载成功，并把下载好的文件保存在临时区域中
						uni.saveFile({ //使用该功能，以将临时文件保存在手机中可长久存储的区域
							tempFilePath: res.tempFilePath,
							success: (saveResult) => {
								// 在保存文件成功后，使用 uni.openDocument 方法打开文件
								console.log("文件保存成功:", saveResult)
								uni.openDocument({
									filePath: saveResult.savedFilePath,
									// fileType: fileType, //这里把预先限定好的文件类型传来
									success: function() {
										console.log("文件打开成功!");
										//至此，手机会从app中跳转到文件预览界面
										//之后可从预览界面返回app中
									},
									fail: function(err) {
										console.log('打开失败', err);
									},
								});
							},
							fail: function(err) {
								console.log('保存文件失败', err);
							},
						});
					}
				} else {
					uni.downloadFile({ //调用官方提供的uni.downloadFile
						url: url, //将刚刚提前准备好的url传过来
						header: {
							//如果需要填写请求头信息则在此处填写
						},
						success: function(res) {
							if (res.statusCode === 200) {
								console.log('下载成功：', res.tempFilePath);

								//下载成功，并把下载好的文件保存在临时区域中
								uni.saveFile({ //使用该功能，以将临时文件保存在手机中可长久存储的区域
									tempFilePath: res.tempFilePath,
									success: (saveResult) => {
										// 在保存文件成功后，使用 uni.openDocument 方法打开文件
										console.log("文件保存成功:", saveResult)
										uni.openDocument({
											filePath: saveResult.savedFilePath,
											// fileType: fileType, //这里把预先限定好的文件类型传来
											success: function() {
												console.log("文件打开成功!");
												//至此，手机会从app中跳转到文件预览界面
												//之后可从预览界面返回app中
											},
											fail: function(err) {
												console.log('打开失败', err);
											},
										});
									},
									fail: function(err) {
										console.log('保存文件失败', err);
									},
								});


							}
						},
						fail: function(err) {
							console.log('下载失败：', err);
						}
					});
				}
				// #endif
			},
			bytesToMB(a, b = 2) {
				if (0 == a || !a) return '0 B';
				const c = 1024,
					d = b || 2,
					e = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
					f = Math.floor(Math.log(a) / Math.log(c));
				return parseFloat((a / Math.pow(c, f)).toFixed(d)) + ' ' + e[f];
			}
		}
	}
</script>

<style lang="scss" scoped>
	.file_upload {
		width: 100%;
	}
</style>